ace.require("ace/ext/language_tools");
var editor = ace.edit("editor");
editor.setOptions({
    enableBasicAutocompletion: true,
    enableSnippets: true,
    enableLiveAutocompletion: true
});
editor.setTheme("ace/theme/xcode");
editor.getSession().setMode("ace/mode/python");
editor.setFontSize(14);

function chart(name ,total_returns_list, benchmark_return_list) {
    Highcharts.setOptions({
    lang:{
           contextButtonTitle:"图表导出菜单",
           decimalPoint:".",
           downloadJPEG:"下载JPEG图片",
           downloadPDF:"下载PDF文件",
           downloadPNG:"下载PNG文件",
           downloadSVG:"下载SVG文件",
           drillUpText:"返回 {series.name}",
           loading:"加载中",
           months:["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],
           noData:"没有数据",
           numericSymbols: [ "千" , "兆" , "G" , "T" , "P" , "E"],
           printChart:"打印图表",
           resetZoom:"恢复缩放",
           resetZoomTitle:"恢复图表",
           shortMonths: [ "一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],
           thousandsSep:",",
           weekdays: ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六","星期天"],
           rangeSelectorZoom:'缩放'
        }
    });

    $(name).highcharts('StockChart', {
        rangeSelector: {
            selected: 2,
            buttons: [{//定义一组buttons,下标从0开始
                    type: 'week',
                    count: 1,
                    text: '1周'
                },
                {
                    type: 'month',
                    count: 1,
                    text: '1月'
                },
                {
                    type: 'month',
                    count: 3,
                    text: '3月'
                },
                {
                    type: 'month',
                    count: 6,
                    text: '6月'
                },
                {
                    type: 'year',
                    count: 1,
                    text: '1年'
                },
                {
                    type: 'all',
                    text: '全部'
                }]
        },
        credits: {
            enabled: false         
        },
         yAxis: {
            minorTickInterval: "auto",
				minorTickLength: 10,
				labels: {
					align: "right",
					format: "{value}%",
					x: -3
				},
				opposite: !0,
				height: "100%",
				lineWidth: 0,
				plotLines: [{
					value: 0,
					width: 1,
					color: "#808080"
				}]

         },
        tooltip: {
             dateTimeLabelFormats: {
					second: "%Y-%m-%d %H:%M:%S",
					minute: "%Y-%m-%d %H:%M",
					hour: "%Y-%m-%d %H:%M",
					day: "%Y-%m-%d",
					week: "%Y-%m-%d",
					month: "%Y-%m",
					year: "%Y"
				},
            pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}%</b><br/>',
            valueDecimals: 2
            },
        xAxis: {
                dateTimeLabelFormats: {
					second: "%Y-%m-%d<br/>%H:%M:%S",
					minute: "%Y-%m-%d<br/>%H:%M",
					hour: "%Y-%m-%d<br/>%H:%M",
					day: "%Y<br/>%m-%d",
					week: "%Y<br/>%m-%d",
					month: "%Y-%m",
					year: "%Y"
				},
            gridLineWidth: 1 ,//纵向网格线宽度
        },
        scrollbar: {
                dateTimeLabelFormats: {
                    second: "%Y-%m-%d %H:%M:%S",
					minute: "%Y-%m-%d %H:%M",
					hour: "%Y-%m-%d %H:%M",
					day: "%Y-%m-%d",
					week: "%Y-%m-%d",
					month: "%Y-%m",
					year: "%Y"
                }
            },
        series: [{
                    name:'基准收益',
                    data:benchmark_return_list,
                    color:"#000080"
                },
                {
                    name:'回测收益',
                    data:total_returns_list,
                    color:"#8B0000"
                }]
    });
}

function logshow(msg){
$(".pannel_in").html('');
  for(var i in msg){
        $(".pannel_in").append('<p><span class="title">SYSTEM</span><span class="tag">INFO</span><span class="msg">'+msg[i]+'</span></p>');
    }

}
function errshow(msg){
  console.log(msg);
  $(".pannel_err").html("");
  for (x in msg)  {
    $(".pannel_err").append("<pre>"+msg[x]+"</pre>");
  }
	$(".menu div").removeClass("on");
	$(".err_log").addClass("on");

//	$(".pannel_err").html("<p>"+msg+"</p>");
  $(".pannel_in").css("display","none");
  $(".pannel_err").css("display","block");
}
Math.mul = function(v1, v2)
{
///<summary>精确计算乘法。语法：Math.mul(v1, v2)</summary>
///<param name="v1" type="number">操作数。</param>
///<param name="v2" type="number">操作数。</param>
///<returns type="number">计算结果。</returns>
  var m = 0;
  var s1 = v1.toString();
  var s2 = v2.toString();
  try
  {
    m += s1.split(".")[1].length;
  }
  catch (e)
  {
  }
  try
  {
    m += s2.split(".")[1].length;
  }
  catch (e)
  {
  }
  
  return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}

$("#compile").click(function(){
    $("#compile").attr('disabled',"false");
	var u_code = editor.getValue();
	var begin = $("#starttime").val();
	var end = $("#endtime").val();
	var u_cash = $(".money input").val();
    NProgress.start();
	$.post("/api/strategybacktest", {
			codeContext: u_code,
			beginTime: begin,
			endTime: end,
			intCash: u_cash,
			back_test: 0
		},
		function(data){
		 NProgress.done();
		 $("#compile").removeAttr("disabled");
			data = JSON.parse(data);
		    if(data.errType == 0){
		    	$(".itme1 span").text(Math.mul(data.totalReturn,100).toFixed(2)+"%");
		    	$(".itme2 span").text(Math.mul(data.annualReturn,100).toFixed(2)+"%");
		    	$(".itme3 span").text(Math.mul(data.benchmarkReturn,100).toFixed(2)+"%");
		    	chart('#backTestChart', data.totalReturnList, data.benchmarkReturnList);
		    	  $.post("/api/outputlog", {


                    },
                    function(data1){
                      logshow(data1["logList"]);

                  },"json");
                 $(".pannel_err").html('');
                 $(".pannel_err").css("display","none");
                 $(".pannel_in").css("display","block");
                 $(".menu div").removeClass("on");
                 $(".yes_log").addClass("on");
		    }
		    else{
		    	$(".itme1 span").text("--");
		    	$(".itme2 span").text("--");
		    	$(".itme3 span").text("--");
		    	chart('#backTestChart', [], []);
		    	errshow(data.errLog);
		    }
	},"json");
})

$(".return-back").click(function(){
    var u_code = editor.getValue();
	var begin = $("#starttime").val();
	var end = $("#endtime").val();
	var u_cash = $(".money input").val();
    console.log(begin);
    NProgress.start();
	$.post("/api/strategybacktest", {
			codeContext: u_code,
			beginTime: begin,
			endTime: end,
			intCash: u_cash,
			back_test: 1
		},
		function(data){
		    NProgress.done();
			data = JSON.parse(data);
			console.log(typeof data);
		    if(data.errType == 0){
		    	window.location.href="/strategy/back-test"
		    }
		    else{
		    	$(".itme1 span").text("--");
		    	$(".itme2 span").text("--");
		    	$(".itme3 span").text("--");
		    	chart([], []);
		    	errshow(data.errLog);
		    }
	},"json");

})
$(".yes_log").click(function(){
  $(".pannel_err").css("display","none");
  $(".pannel_in").css("display","block");
  $(".menu div").removeClass("on");
  $(".yes_log").addClass("on");
})
$(".err_log").click(function(){
  $(".pannel_err").css("display","block");
  $(".pannel_in").css("display","none");
  $(".menu div").removeClass("on");
  $(".err_log").addClass("on");
})
$("#save").click(function(){
    NProgress.start();
    var u_code = editor.getValue();
    var begin = $("#starttime").val();
	var end = $("#endtime").val();
	var u_cash = $(".money input").val();
	var strategy_name = $(".bar_title input").val();

    $.post("/api/strategysave",{
        codeContext:u_code,
        beginDate:begin,
        endDate:end,
        intCash:u_cash,
        strategyName:strategy_name
        },function(data){
          NProgress.done();
          $("#save").val("已保存");
          $("#save").attr('disabled',"false");
          setTimeout(function(){
            $("#save").val("保存");
            $("#save").removeAttr("disabled");
          },2000)
    })
})

$(".e_left_head span").click(function(){
     $(".tool-list").toggle();
});

var strategy ={
     changeFontSize:function(arg){
        editor.setFontSize(arg);
        $(".tool-list").hide();
     },

     changeTheme:function(arg){
        editor.setTheme("ace/theme/"+arg);
        $(".tool-list").hide();
     },

     changeKeyboard:function(arg){
        //alert(arg);
        editor.setKeyboardHandler(arg);
        $(".tool-list").hide();
     }
 }


var picker = new Pikaday(
    {
        field: document.getElementById('starttime'),
        firstDay: 1,
        minDate: new Date('2010/01/01'),
        maxDate: new Date('2020/12/31'),
        yearRange: [2000,2020]
    });
 // picker.toString('YYYY/MM/DD');
var picker1 = new Pikaday(
{
    field: document.getElementById('endtime'),
    firstDay: 1,
    minDate: new Date('2010/01/01'),
    maxDate: new Date('2020/12/31'),
    yearRange: [2000,2020]
});

// $(".bar_title input").on('input',function(e){  
//    $("#save").val("保存");
//    $("#save").removeAttr("disabled");
// });  

// editor.on("change", function(){
//   $("#save").val("保存");
//   $("#save").removeAttr("disabled");
// })

function onCopy(){
    var u_code = editor.getValue();
    var begin = $("#starttime").val();
	var end = $("#endtime").val();
	var u_cash = $(".money input").val();
	var strategy_name = $(".bar_title input").val();

     $.post("/api/strategycopy",{
        codeContext:u_code,
        beginDate:begin,
        endDate:end,
        intCash:u_cash,
        strategyName:strategy_name
        },function(data){
         if (data.state == '1'){
            window.location.href =
            '/strategy/edit/?strategyId='+ data['strategyId'] + '&versionId=' + data['versionId'];
         }
    })
}


